package com.webonn.frame.util;

import com.google.common.collect.Maps;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;
import com.webonn.frame.conf.SMSConfiguration;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.concurrent.ConcurrentMap;

/**
 *  Created by Administrator on 2016/6/5.
 *  发送短信
 */
public class SmsController {
    private static SmsController theInstance;
    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(SmsController.class);
    private static ConcurrentMap<String, CodeInfo> codeHolder = Maps.newConcurrentMap();
    private TaobaoClient client;
    private String appName;
    private String signName;
    private String sms_template_register;
    private String sms_template_error;
    private String sms_template_changepwd;
    private String sms_template_auth;
    private long expiry;

    public Boolean authcode(int code, String phone){
        CodeInfo codeInfo =  codeHolder.get(phone);
        if(codeInfo != null && codeInfo.getCode() == code) {
            if (new Date().getTime() - codeInfo.getCreateTime().getTime() < expiry) {
                //codeHolder.remove(phone);
                return true;
            } else {
                codeHolder.remove(phone);
                return false;
            }
        }else{
            return false;
        }
    }

    /*
     * send code to phone
     */
    public Boolean sendcode(String rec_num) {
        if(client == null) {
            init(new SMSConfiguration());
        }
        CodeInfo codeInfo =  codeHolder.get(rec_num);

        if(codeInfo != null && (System.currentTimeMillis() - codeInfo.createTime.getTime()) < 30 * 1000){
            throw new EntityError("Too frequent operation. Please try again later", 403);
            //throw new EntityError("", 404);
        }

        AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
        int code = new Double(Math.random() * 9000 + 1000).intValue();

        req.setExtend("123456");
        req.setSmsType("normal");

        req.setSmsParamString("{\"code\":\"" + code + "\"}");
        req.setRecNum(rec_num);
        String smsTemplate = sms_template_auth;
        req.setSmsFreeSignName(signName);
        req.setSmsTemplateCode(smsTemplate);
        try {
            AlibabaAliqinFcSmsNumSendResponse rsp = client.execute(req);
            codeHolder.put(rec_num, new CodeInfo(code, new Date()));
            return rsp.getErrorCode() == null && rsp.getResult().getSuccess();
        }catch (ApiException e){
            return false;
        }
    }

    public Boolean sendErrorMsg(String rec_num, String errorType) {
        if(client == null) {
            init(new SMSConfiguration());
        }

        AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();

        req.setExtend("123456");
        req.setSmsType("normal");
        req.setSmsParamString("{\"errortype\":\"" + errorType + "\"}");
        req.setRecNum(rec_num);
        req.setSmsFreeSignName(signName);
        req.setSmsTemplateCode(sms_template_error);

        try {
            AlibabaAliqinFcSmsNumSendResponse rsp = client.execute(req);
            return rsp.getErrorCode() == null && rsp.getResult().getSuccess();
        }catch (ApiException e){
            return false;
        }
    }

    class CodeInfo{
        private int code;
        private Date createTime;
        private boolean useable;

        CodeInfo(int code, Date createTime){
            this.code = code;
            this.createTime = createTime;
            this.useable = true;
        }

        public int getCode() {
            return code;
        }

        public void setCode(int code) {
            this.code = code;
        }

        public Date getCreateTime() {
            return createTime;
        }

        public void setCreateTime(Date createTime) {
            this.createTime = createTime;
        }

        public boolean isUseable() {
            return useable;
        }

        public void setUseable(boolean useable) {
            this.useable = useable;
        }
    }

    public void init(SMSConfiguration conf) {
        //SMSConfiguration conf = new SMSConfiguration();
        client = new DefaultTaobaoClient(conf.smsuri, conf.smsAppKey, conf.smsSecret);
        appName = conf.appName;
        sms_template_auth = conf.sms_template_auth;
        sms_template_error = conf.sms_template_error;
        signName = conf.signName;
        expiry = conf.expiry;
    }

    /**
     * Get singleton instance
     *
     * @return the instance
     */
    public static synchronized SmsController getInstance() {
        if (theInstance == null) {
            theInstance = new SmsController();
        }
        return theInstance;
    }

    public TaobaoClient getClient() {
        return client;
    }

    public void setClient(TaobaoClient client) {
        this.client = client;
    }

    public String getAppName() {
        return appName;
    }

    public void setAppName(String appName) {
        this.appName = appName;
    }

    public String getSms_template_register() {
        return sms_template_register;
    }

    public void setSms_template_register(String sms_template_register) {
        this.sms_template_register = sms_template_register;
    }

    public String getSms_template_changepwd() {
        return sms_template_changepwd;
    }

    public void setSms_template_changepwd(String sms_template_changepwd) {
        this.sms_template_changepwd = sms_template_changepwd;
    }
}
